package edu.uwm.RobberKnight.View;

import java.awt.Color;
import java.awt.Graphics;
import java.util.LinkedList;

import javax.swing.JPanel;

import edu.uwm.RobberKnight.Controller.RobberKnightsController;
import edu.uwm.RobberKnight.Model.Player;
import edu.uwm.RobberKnight.Model.Tile;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class HandsView extends JPanel {

	private static final long serialVersionUID = 2154651511538228993L;
	
	private RobberKnightsController _controller;
	private boolean _showFaces;
	private Player _lastPlayer = null;
	private LinkedList<GuiTile> _tiles;
	
	public HandsView(RobberKnightsController controller) {
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				for(GuiTile tile : _tiles) {
					if(tile.containsPoint(e.getX(), e.getY())) { 
						_controller.setSelectedTile(tile.getTile());
						return;
					}
				}
				_controller.setSelectedTile(null);
			}
		});
		_controller = controller;
		_tiles = new LinkedList<GuiTile>();
	}
	
	@Override
	public void paint(Graphics g) {
		//fill background
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, getWidth(), getHeight());
		if(_controller != null && _controller.getCurrentPlayer() != null) {
			if(_controller.getCurrentPlayer() != _lastPlayer) {
				_showFaces = false;
				_lastPlayer = _controller.getCurrentPlayer();
			}
			for(int i = 0; i < _tiles.size(); i++) {
				GuiTile tile = _tiles.get(i);
				tile.setY(10);
				tile.setX((((i*2)+1) * getWidth() / (_tiles.size() * 2)) - (GuiTile.TILE_SIZE / 2));
				if(tile.getTile() == _controller.getSelectedTile()) {
					g.setColor(Color.YELLOW);
					g.fillRect(tile.getX() - 5, tile.getY() - 5, GuiTile.TILE_SIZE + 10, GuiTile.TILE_SIZE + 10);
				}
				if(_showFaces)
					tile.drawTileFace(g, false);
				else
					tile.drawTileBack(g);
			}
		}
	}
	
	public void updateState(long time) {
		if(_controller.getCurrentPlayer() != null)
			updateTileCollection(_controller.getCurrentPlayer(), _tiles);
	}
	
	public static void updateTileCollection(Player player, LinkedList<GuiTile> ourTiles) {
		LinkedList<GuiTile> toRemove = new LinkedList<GuiTile>();
		for(GuiTile gt : ourTiles)
			toRemove.add(gt);
		for(Tile tile : player.getHand()) {
			boolean found = false;
			for(GuiTile gt : ourTiles) {
				if(gt.getTile() == tile) {
					toRemove.remove(gt);
					found = true;
				}	
			}
			if(!found)
				ourTiles.add(new GuiTile(tile));
		}
		for(GuiTile tile : toRemove) {
			ourTiles.remove(tile);
		}
	}
	
	public boolean getShowFaces() {
		return _showFaces;
	}
	
	public void setShowFaces(boolean show) {
		_showFaces = show;
	}
}
